<template>
  <div class="field-mapping">
    <el-table :data="fieldMappingList" style="width: 100%" v-loading="loading">
      <el-table-column prop="sourceField" label="源字段" width="150" />
      <el-table-column prop="targetField" label="目标字段" width="150" />
      <el-table-column prop="fieldType" label="字段类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getFieldTypeTag(row.fieldType)">
            {{ getFieldTypeText(row.fieldType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="transformRule" label="转换规则" min-width="200" show-overflow-tooltip />
      <el-table-column prop="isRequired" label="是否必填" width="80">
        <template #default="{ row }">
          <el-tag :type="row.isRequired ? 'danger' : 'info'">
            {{ row.isRequired ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button 
            :type="row.status === 1 ? 'danger' : 'success'" 
            link 
            @click="handleToggleStatus(row)"
          >
            {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pageInfo.pageNum"
      v-model:page-size="pageInfo.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑字段映射对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="mappingFormRef"
        :model="mappingForm"
        :rules="mappingRules"
        label-width="100px"
      >
        <el-form-item label="源字段" prop="sourceField">
          <el-input v-model="mappingForm.sourceField" placeholder="请输入源字段名称" />
        </el-form-item>
        <el-form-item label="目标字段" prop="targetField">
          <el-input v-model="mappingForm.targetField" placeholder="请输入目标字段名称" />
        </el-form-item>
        <el-form-item label="字段类型" prop="fieldType">
          <el-select v-model="mappingForm.fieldType" placeholder="请选择字段类型" style="width: 100%">
            <el-option label="字符串" value="STRING" />
            <el-option label="数字" value="NUMBER" />
            <el-option label="日期" value="DATE" />
            <el-option label="布尔值" value="BOOLEAN" />
            <el-option label="数组" value="ARRAY" />
            <el-option label="对象" value="OBJECT" />
          </el-select>
        </el-form-item>
        <el-form-item label="转换规则" prop="transformRule">
          <el-input 
            v-model="mappingForm.transformRule" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入转换规则，如：toUpperCase()、formatDate('yyyy-MM-dd')等"
          />
        </el-form-item>
        <el-form-item label="是否必填" prop="isRequired">
          <el-radio-group v-model="mappingForm.isRequired">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="mappingForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="mappingForm.description" 
            type="textarea" 
            :rows="2" 
            placeholder="请输入字段映射描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { getFieldMappingList, createFieldMapping, updateFieldMapping, deleteFieldMapping, updateFieldMappingStatus } from '@/api/engine'
import type { FieldMapping } from '@/types/api'

const loading = ref(false)
const fieldMappingList = ref<FieldMapping[]>([])
const total = ref(0)

const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10
})

const dialogVisible = ref(false)
const submitLoading = ref(false)
const mappingFormRef = ref<FormInstance>()

const mappingForm = reactive({
  id: undefined as number | undefined,
  sourceField: '',
  targetField: '',
  fieldType: 'STRING' as 'STRING' | 'NUMBER' | 'DATE' | 'BOOLEAN' | 'ARRAY' | 'OBJECT',
  mappingRule: '',
  transformRule: '',
  isRequired: false,
  status: 1,
  description: ''
})

const mappingRules: FormRules = {
  sourceField: [{ required: true, message: '请输入源字段', trigger: 'blur' }],
  targetField: [{ required: true, message: '请输入目标字段', trigger: 'blur' }],
  fieldType: [{ required: true, message: '请选择字段类型', trigger: 'change' }],
  mappingRule: [{ required: true, message: '请输入映射规则', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const dialogTitle = computed(() => 
  mappingForm.id ? '编辑字段映射' : '新增字段映射'
)

const getFieldTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    'STRING': 'primary',
    'NUMBER': 'success',
    'DATE': 'warning',
    'BOOLEAN': 'info',
    'ARRAY': 'danger',
    'OBJECT': 'primary'
  }
  return tagMap[type] || 'info'
}

const getFieldTypeText = (type: string) => {
  const textMap: Record<string, string> = {
    'STRING': '字符串',
    'NUMBER': '数字',
    'DATE': '日期',
    'BOOLEAN': '布尔值',
    'ARRAY': '数组',
    'OBJECT': '对象'
  }
  return textMap[type] || type
}

const fetchFieldMappingList = async () => {
  loading.value = true
  try {
    const response = await getFieldMappingList(pageInfo)
    fieldMappingList.value = response.records
    total.value = response.total
  } catch (error) {
    ElMessage.error('获取字段映射列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  mappingForm.id = undefined
  mappingForm.sourceField = ''
  mappingForm.targetField = ''
  mappingForm.fieldType = 'STRING' as 'STRING' | 'NUMBER' | 'DATE' | 'BOOLEAN' | 'ARRAY' | 'OBJECT'
  mappingForm.mappingRule = ''
  mappingForm.transformRule = ''
  mappingForm.isRequired = false
  mappingForm.status = 1
  mappingForm.description = ''
  dialogVisible.value = true
}

const handleEdit = (row: FieldMapping) => {
  mappingForm.id = row.id
  mappingForm.sourceField = row.sourceField
  mappingForm.targetField = row.targetField
  mappingForm.fieldType = row.fieldType as 'STRING' | 'NUMBER' | 'DATE' | 'BOOLEAN' | 'ARRAY' | 'OBJECT'
  mappingForm.mappingRule = row.mappingRule
  mappingForm.transformRule = row.transformRule || ''
  mappingForm.isRequired = row.isRequired || false
  mappingForm.status = row.status
  mappingForm.description = row.description || ''
  dialogVisible.value = true
}

const handleToggleStatus = async (row: FieldMapping) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '禁用' : '启用'}字段映射"${row.sourceField} -> ${row.targetField}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await updateFieldMappingStatus(row.id, row.status === 1 ? 0 : 1)
    ElMessage.success(`${row.status === 1 ? '禁用' : '启用'}成功`)
    fetchFieldMappingList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleDelete = async (row: FieldMapping) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除字段映射"${row.sourceField} -> ${row.targetField}"吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await deleteFieldMapping(row.id)
    ElMessage.success('删除成功')
    fetchFieldMappingList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!mappingFormRef.value) return
  
  try {
    await mappingFormRef.value.validate()
    submitLoading.value = true
    
    if (mappingForm.id) {
      await updateFieldMapping(mappingForm.id, mappingForm)
      ElMessage.success('更新成功')
    } else {
      await createFieldMapping(mappingForm)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchFieldMappingList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  mappingFormRef.value?.resetFields()
}

const handleSizeChange = (val: number) => {
  pageInfo.pageSize = val
  fetchFieldMappingList()
}

const handleCurrentChange = (val: number) => {
  pageInfo.pageNum = val
  fetchFieldMappingList()
}

onMounted(() => {
  fetchFieldMappingList()
})
</script>

<style scoped>
.field-mapping {
  padding: 20px;
}
</style>